﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net.Sockets;

namespace ControlClient
{
    public class SocketClient
    {
        private TcpClient client;
        private string ip = "10.0.5.100";
        private int port = 23456;
        public EventHandler<SocketAsyncEventArgs> Recevie_Even;
        public SocketClient()
        {
            client = new TcpClient();
            client.BeginConnect(ip, port,new AsyncCallback(Listener), null);
        }

        /// <summary>
        /// 客户端链接状态
        /// </summary>
        public bool Connectioned {
            get {
                if (client.Client == null)
                {
                    return false;
                }
                return client.Connected;
            }
        }

        public bool Connection()
        {
            client = new TcpClient();
            client.Connect(ip, port);
            if (client.Connected)
            {
                Listener(null);
            }
            return client.Connected;
        }

        public void Close()
        {
            client.Close();
        }

        private void Listener(object obj)
        {
            SendAsync("cmd$control01$in", null);
            while (true)
            {
                try
                {
                    var socket = client.Client;
                    byte[] buffer = new byte[2048];
                    socket.Receive(buffer);
                    string req = Encoding.UTF8.GetString(buffer);
                    Recevie_Even(req, null);
                }
                catch (Exception)
                {
                    
                }
            }
        }

        

        public void SendAsync(string msg, EventHandler<SocketAsyncEventArgs> method)
        {
            Socket socket = client.Client;
            SocketAsyncEventArgs sendAsync = new SocketAsyncEventArgs();
            if (method != null)
            {
                sendAsync.Completed += method;
            }
            byte[]buffer=Encoding.UTF8.GetBytes(msg);
            sendAsync.SetBuffer(buffer, 0, buffer.Length);
            socket.SendAsync(sendAsync);
        }

        
    }
}
